package com.forest.datachangetracker.utils;

import com.forest.datachangetracker.annotation.AuditField;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * 获取实体字段值
 * @author forest
 */
public class EntityValueExtractor {

    public static List<String>  extractEntityFieldNames(Class<?> entityClass) {
        if (entityClass == null) {
            return new ArrayList<>();
        }
        List<String> fieldNames = new ArrayList<>();
        // 使用反射获取实体字段值，优先获取有@AuditField注解的字段
        boolean hasAuditField = false;
        for (Field field : entityClass.getDeclaredFields()) {
            // 检查是否有AuditField注解
            if (field.isAnnotationPresent(AuditField.class)) {
                AuditField auditField = field.getAnnotation(AuditField.class);
                if (auditField.ignore()) {
                    continue; // 忽略该字段
                }
                String fieldName = field.getName();
                fieldNames.add(fieldName);
                hasAuditField = true;
            }
        }

        // 如果没有找到带注解的字段，则获取所有非静态字段
        if (!hasAuditField) {
            for (Field field : entityClass.getDeclaredFields()) {
                // 跳过静态字段
                if (java.lang.reflect.Modifier.isStatic(field.getModifiers())) {
                    continue;
                }
                fieldNames.add(field.getName());
            }
        }
        return fieldNames;
    }
}
